package org.zzy.webhook;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.zzy.entity.WxMarkdownEntity;

import java.io.IOException;
import java.util.List;

import static org.zzy.util.HttpClientUtils.createHttpClient;

@Slf4j
public class WxClient {
    private final static String  key_yhwl_test   = "****-*******--*******-******";
    private final static CloseableHttpClient httpClient = createHttpClient();

    /**
     * @param mdMessage Markdown 格式的消息
     * @throws RuntimeException 如果调用 Webhook 失败
     */
    public static void sendMarkdownMessage(String mdMessage, List<String> userList) {

        WxMarkdownEntity.MarkdownDTO markdownDTO = new WxMarkdownEntity.MarkdownDTO();
        markdownDTO.setContent(mdMessage);
        markdownDTO.setMentioned_mobile_list(userList);
        WxMarkdownEntity wxMarkdownEntity = new WxMarkdownEntity();
        wxMarkdownEntity.setMsgtype("markdown");
        wxMarkdownEntity.setMarkdown(markdownDTO);
        StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(wxMarkdownEntity), ContentType.APPLICATION_JSON);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + key_yhwl_test
        HttpUriRequest post = RequestBuilder.post()
                .setUri(url)
                .setEntity(stringEntity)
                .build();

        try {
            String result = sendRequest(httpClient, post);
            log.debug("收到：{}", result);
        } catch (IOException e) {
            throw new RuntimeException("调用 Webhook 失败", e);
        }
    }

    private static String sendRequest(CloseableHttpClient httpClient, HttpUriRequest request) throws IOException {
        String content;

        try (CloseableHttpResponse response = httpClient.execute(request)) {
            HttpEntity entity = response.getEntity();
            content = EntityUtils.toString(entity);
            log.debug("收到：{}", content);
        }
        return content;
    }


}
